import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import {RouterService} from '@kylin/router';
import {LoginService} from './login.service';
import {NzMessageService} from 'ng-zorro-antd';
import {CacheService} from '@kylin/cache';
import * as _ from 'lodash';

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less']
})

export class LoginComponent implements OnInit, AfterViewInit {

    loginForm: FormGroup;
    loading = false;
    state = true;
    @ViewChild('verificationCode') verificationCode;

    constructor(private routerService: RouterService,
                private fb: FormBuilder,
                private loginService: LoginService,
                private message: NzMessageService,
                private cacheService: CacheService
    ) {

    }

    /**
     * 此方法用创建响应式表单
     */
    ngOnInit(): void {
        this.loginFormInit();
    }

    ngAfterViewInit(): void {

    }

    private loginFormInit() {
        this.loginForm = this.fb.group({
            username: ['admin', [Validators.required]],
            password: ['admin', [Validators.required]],
            validCode: [null, [Validators.required]]
        });
    }

    /**
     * 此方法用来提交登陆表单
     */
    submitForm(): void {
        if (!this.loginForm.valid) {
            return;
        }
        this.loading = true;
        const data = {};
        _.forEach(this.loginForm.value, (value, key) => {
            if (key === 'validCode') {
                data['deviceId'] = value['deviceId'];
                data['validCode'] = value['validCode'];
            } else {
                data[key] = value;
            }
        });
        this.loginService.doLogin(data)
            .then(res => {
                this.loading = false;
                if (res.resp_code === '10000') {
                    this.cacheService.clear();
                    this.cacheService.set('access_token', res.data.access_token);
                    this.cacheService.set('refresh_token', res.data.refresh_token);
                    const expires_time = new Date().getTime() + res.data.expires_in * 1000;
                    this.cacheService.set('expires_time', expires_time);

                    this.message.success('登录成功!', {nzDuration: 1000});
                    setTimeout(() => {
                        this.routerService.navigate('/home');
                    }, 1000)
                } else {
                    this.message.error(res.resp_msg);
                    this.fetchVerificationCode();
                }
            })
            .catch(err => {
                this.loading = false;
                this.message.create('error', `登陆失败`);
            });
    }

    private fetchVerificationCode() {
        this.verificationCode.fetchValidCode();
    }

}

